package ink.xiaobaibai.config;

import com.alibaba.fastjson.JSON;
import ink.xiaobaibai.common.MySecurity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-08-08
 **/

@Aspect
@Component
@Slf4j
public class RequestParamsConfig {

    @Autowired
    private HttpServletRequest request;

    @Pointcut(value = "execution(public * ink.xiaobaibai.controller.*.*.*(..)) || execution(public * ink.xiaobaibai.controller.*.*(..))")
    public void point() {
    }

    @Before(value = "point()")
    public void processLog(JoinPoint joinPoint) {
        String requestURI = this.request.getRequestURI();
        Object[] args = joinPoint.getArgs();
        Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.stream(args);
        List<Object> logArgs = stream
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
                .collect(Collectors.toList());
        log.info("url:{}\tuserId:{}\targs:{}", requestURI, MySecurity.getUserId(), JSON.toJSONString(logArgs));
    }

}
